package org.lztvn.elearning.controllers;

import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.lztvn.elearning.entities.Command;
import org.lztvn.elearning.entities.CommandeLine;
import org.lztvn.elearning.entities.Product;
import org.lztvn.elearning.service.ICommandLineService;
import org.lztvn.elearning.service.ICommandeService;
import org.lztvn.elearning.service.Utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CommandController extends AppController{
      
	   @Autowired
	   ICommandeService commSer;
	   
	   @Autowired
	   ICommandLineService commLineSer;
	   
	   Utility util;
	   
	   private void init() {
			ApplicationContext context = new ClassPathXmlApplicationContext(
					"applicationContext.xml");
			this.util = (Utility) context.getBean("util");
		}
	
	   @RequestMapping(value = "/commands", method = RequestMethod.GET)
		public ModelAndView index(Model model, HttpSession session) {
		    init();
			if (util.checkSession(session) == false) {
				return new ModelAndView("redirect:login");
			} else {
				model.addAttribute("commands", commSer.listCommand(0, 0));
				return new ModelAndView("commands");
			}

		}
	   
		@RequestMapping(value = "/delComm")
		public ModelAndView supp(Long idCom, Model model, HttpSession session) {
			init();
			if (util.checkSession(session) == false) {
				return new ModelAndView("redirect:login");
			} else {
				commSer.delCommande(idCom);
				model.addAttribute("commands", commSer.listCommand(0, 0));
				return new ModelAndView("commands");
			}
		}
		
		@RequestMapping(value = "/comd_detail")
		public ModelAndView edit(Long idCom, Model model, HttpSession session) {
			init();
			if (util.checkSession(session) == false) {
				return new ModelAndView("redirect:login");
			} else {
				Command c = commSer.getCommande(idCom);
				List<CommandeLine> lstcmdl = commLineSer.listCommandLineByCmdId(idCom, 1, 1);
				Hashtable<Product, Integer>  lstprod =  new Hashtable<Product, Integer>();
				double total = 0;
				for (CommandeLine lst : lstcmdl) {
					Product pro = lst.getProd();
					Integer qty = lst.getQty();
					lstprod.put(pro, qty);
					total += (pro.getPrice())*qty;
				}
				model.addAttribute("lstcmdl", lstprod);
				model.addAttribute("total", total);
				//model.addAttribute("editedCor", c);
				model.addAttribute("command", c);
			    
				
				return new ModelAndView("command_detail");
			}
		}
}
